package com.itheima.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.vo.PageResult;
import com.itheima.pojo.domain.Student;
import com.itheima.pojo.dto.StudentPageQueryDTO;
import com.itheima.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    /**
     * 分页查询
     * @param spqdto
     * @return
     */
    @Override
    public PageResult<Student> list(StudentPageQueryDTO spqdto) {
        //开始分页
        PageHelper.startPage(spqdto.getPage(),spqdto.getPageSize());

        //查询分页数据
        Page<Student> students = studentMapper.list(spqdto);

        //封装分页结果
        PageResult<Student> studentPageResult = new PageResult<>(students.getTotal(), students.getResult());

        return studentPageResult;
    }

    /**
     * 根据id查询学生信息
     * @param id
     * @return
     */
    @Override
    public Student getStudentInfoById(Integer id) {

        Student student = studentMapper.listById(id);

        return student;
    }

    /**
     * 添加学生信息
     * @param student
     */
    @Override
    public void addStudentInfo(Student student) {

        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());


        studentMapper.addStudentInfo(student);


    }

    /**
     * 删除学生信息
     * @param ids
     */

    @Override
    public void deleteStudentInfo(List<Integer> ids) {

        studentMapper.deleteByIds(ids);

    }

    /**
     * 修改学生信息
     * @param student
     */
    @Override
    public void updateStudentInfo(Student student) {

        student.setUpdateTime(LocalDateTime.now());
        studentMapper.updateStudentInfo(student);
    }

    @Override
    public void updateViolation(Integer id ,Short score) {
        //创建学生类将id和score设置到学生类中再将学生类传给updateStudentInfo方法实现方法复用而不用重新写sql
        Student student = new Student();
        student.setId(id);

        //通过id查询到原来的分数
        Short oldSocre  = studentMapper.selStudentScore(id);
        //将原来的分数和传入的分数进行相加再设置给学生类
        student.setViolationScore(Short.valueOf((short)(oldSocre + score)));
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.updateStudentInfo(student);

        //根据id查询扣分次数
        short counts = studentMapper.selStudentCount(id);
        //如果是加分（加负的扣分次数为加分）则不增加违纪次数
        if (score<=0){
            counts--;
        }
        //更新扣分次数
        studentMapper.updateViolation(id,counts);

    }
}
